<template>
  <c-back-wrap :loading="loading" go-page="经销商档案新建管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'新建'">
    <QupFormContainer :column="3">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="130px">
        <el-form-item prop="officeCode" label="办事处">
          <c-common-search-office
            v-model="formData.officeCode"
            :label.sync="formData.officeName"
            :office-type-code.sync="formData.officeTypeCode"
            :office-type-name.sync="formData.officeTypeName"
            :principal-code.sync="formData.personCode"
            :principal-name.sync="formData.personName"
            :disabled="isEdit"
            @change="handleOfficeChange"
          />
        </el-form-item>
        <el-form-item prop="officeTypeName" label="办事处类别">
          <span>{{ formData.officeTypeName }}</span>
        </el-form-item>
        <el-form-item prop="personName" label="办事处负责人">
          <span>{{ formData.personName }}</span>
        </el-form-item>
        <el-form-item prop="isOtherReceiveManagerKnow" label="是否需要其他业务客户经理接收知晓" label-width="210px">
          <el-switch v-model="formData.isOtherReceiveManagerKnow" :active-value="1" :inactive-value="0" @change="handleChange" />
        </el-form-item>
        <el-form-item v-show="showReceiveManager" prop="receiveManagerCode" label="接收客户经理">
          <c-common-search-person-by-office
            v-model="formData.receiveManagerCode"
            :label.sync="formData.receiveManagerName"
            :person-tel_res.sync="formData.receiveManagerTel"
            :mgr-type_res.sync="formData.receiveManagerTypeCode"
            :mgr-type-name_res.sync="formData.receiveManagerTypeName"
            :query-office-code="formData.officeCode"
            :depend-on-observe="formData.officeCode"
            :disabled="!formData.officeCode"
            :start-observe="startObserve"
          />
        </el-form-item>
        <template v-if="showReceiveManager">
          <el-form-item prop="receiveManagerName" label="接收客户经理编码">
            <span>{{ formData.receiveManagerCode }}</span>
          </el-form-item>
          <el-form-item prop="receiveManagerTypeName" label="接收客户经理类型">
            <span>{{ formData.receiveManagerTypeName }}</span>
          </el-form-item>
          <el-form-item prop="receiveManagerTel" label="接收客户经理电话">
            <span>{{ formData.receiveManagerTel }}</span>
          </el-form-item>
        </template>
        <el-form-item prop="submitAnOpinion" label="提报意见" :span="24">
          <el-input v-model="formData.submitAnOpinion" type="textarea" show-word-limit maxlength="512" :autosize="{minRows: 3}" placeholder="提报意见" clearable />
        </el-form-item>
      </el-form>
    </QupFormContainer>
    <c-title title="经销商基本信息">
      <QupFormContainer :column="3">
        <el-form ref="form2" :model="formData" :rules="formRules2" label-width="110px">
          <el-form-item prop="customerName" label="经销商系统名称">
            <el-input v-model.trim="formData.customerName" placeholder="经销商系统名称" clearable />
          </el-form-item>
          <el-form-item prop="legalPerson" label="经销商姓名">
            <el-input v-model.trim="formData.legalPerson" placeholder="经销商姓名" clearable />
          </el-form-item>
          <el-form-item prop="credentialNo" label="经销商身份证号">
            <el-input v-model="formData.credentialNo" placeholder="经销商身份证号" clearable />
          </el-form-item>
          <!-- <el-form-item prop="disAddr" label="身份证详细地址" :span="24">
            <el-input v-model="formData.disAddr" placeholder="身份证详细地址" type="textarea" show-word-limit maxlength="200" :autosize="{minRows:2}" clearable />
          </el-form-item> -->
          <el-form-item prop="cooperateStart" label="合作起始日期">
            <el-date-picker v-model="formData.cooperateStart" operator="<=" :limit="new Date()" value-format="yyyy-MM-dd HH:mm:ss" type="date" clearable />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS050" label="身份证正面图片" :span="24">
            <c-file-list v-model="formData.ACCESS050" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS050" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS051" label="身份证反面图片" :span="24">
            <c-file-list v-model="formData.ACCESS051" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS051" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS052" label="资金安全告知函" :span="24">
            <c-file-list v-model="formData.ACCESS052" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS052" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS053" label="签字签章函" :span="24">
            <c-file-list v-model="formData.ACCESS053" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS053" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS054" label="收货地址确认单" :span="24">
            <c-file-list v-model="formData.ACCESS054" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS054" />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="经销商-收货地址">
      <AddrTable ref="addrTable" title="经销商-收货地址" :table-data="formData.addressDTOS" type="edit" :start-observe="startObserve" />
    </c-title>
    <c-title title="经销商-联系人">
      <ContactsTable ref="contactsTable" title="经销商-联系人" :table-data="disContactsTableData" type="edit" />
    </c-title>
    <c-title>
      <div slot="title" style="display:flex;align-items:center;">
        <span class="title" style="margin-right: 5px">是否合伙经营</span>
        <el-switch v-model="formData.isPartnership" :active-value="1" :inactive-value="0" />
      </div>
      <PartnershipTable v-show="[1,'1'].includes(formData.isPartnership)" ref="partnershipTable" title="合伙经营" :table-data="formData.partnerDTOS" type="edit" />
    </c-title>
    <c-title title="交接信息">
      <QupFormContainer :column="1">
        <el-form ref="form5" :model="formData" :rules="formRules4" label-width="110px">
          <el-form-item prop="isMarketConnect" label="是否经销商交接">
            <!-- <el-switch v-model="formData.isMarketConnect" :active-value="1" :inactive-value="0" /> -->
            <c-dict-select v-model="formData.isMarketConnect" dict-type-code="BOOLEANS" :clearable="false" />
          </el-form-item>
          <template v-if="[1,'1'].includes(formData.isMarketConnect)">
            <el-form-item prop="distributionTable1" label="" label-width="0" style="width:100%">
              <DistributionTable ref="distributionTable" filter-q-y-q-j-k-u title="交接信息" :table-data="formData.handoverDTOS" :office-code="formData.officeCode" :hidden-column="['toAccountCode', 'toAccountName', 'fromShopCode', 'fromShopName']" type="edit" @on-customer-change="handleOnCustomerChange" />
            </el-form-item>
            <el-form-item prop="isHandoverDistribution" label="是否交接分销客户" style="width:100%">
              <div class="handover">
                <c-dict-select v-model="isHandoverDistribution" dict-type-code="BOOLEANS" :clearable="false" />
                <span v-show="[1,'1'].includes(isHandoverDistribution)" class="tip">*请及时提报《轻居客户档案新建流程》</span>
              </div>
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS058" label="经销商交接证明" :span="24">
              <c-file-list v-model="formData.ACCESS058" direct-del :model-id="id" view-type="list" type-code="ACCESS058" tip="交接证明签订一式三份，双方各自保留一份，邮寄公司一份" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS059" label="经销商关系证明" :span="24">
              <c-file-list v-model="formData.ACCESS059" direct-del :model-id="id" view-type="list" type-code="ACCESS059" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" key="ACCESS111" prop="ACCESS111" label="交接双方现场签订照片" label-width="160px" :span="24">
              <c-file-list v-model="formData.ACCESS111" direct-del :model-id="id" view-type="list" type-code="ACCESS111" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" prop="1" label="交接双方现场签订照片模板下载" label-width="180px" :span="24">
              <div class="template-down" @click.stop="handleDownTemplate(ACCESS111.id)">
                <span>交接双方现场签订照片模板下载</span>
                <i class="el-icon-download" />
              </div>
            </el-form-item>
          </template>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="门店基本信息">
      <el-form ref="form6" :model="formData" :rules="formRules6" label-width="140px">
        <el-form-item v-if="hasIsMarketConnect" prop="isTakeOverTheOriginalStore" label="是否接管原商家门店">
          <c-dict-select v-model="formData.isTakeOverTheOriginalStore" dict-type-code="BOOLEANS" clearable placeholder="是否接管原商家门店" @change="handleTakeOverChange" />
        </el-form-item>
        <el-form-item v-if="isTakeOver" prop="1" label="" label-width="0">
          <c-title title="新增门店信息">
            <ShopTable ref="shopTable" :table-data="customerShopData" @on-takeover-change="handleOnTakeoverChange" />
          </c-title>
          <c-title title="门店联系人">
            <ShopContactTable ref="shopContactTable" :table-data="shopContactsData" :shop-data="customerShopData" />
          </c-title>
        </el-form-item>
      </el-form>
      <QupFormContainer v-if="!isTakeOver" :column="3">
        <el-form ref="form3" :model="formDataShopDTO" :rules="formRules3" label-width="140px">
          <el-form-item prop="businessType" label="门店经营业务类型" :span="24">
            <!-- v-model="formDataShopDTO.businessType"
              :label.sync="formDataShopDTO.businessTypeName" -->
            <c-common-search-mdm
              placeholder="请选择"
              cust-doc-code="QY037"
              @data-change="handleBusinessTypeDataChange"
            >
              <template v-slot="data">
                <el-checkbox-group v-model="formDataShopDTO.businessType" @change="handleBusinessChange">
                  <el-checkbox v-for="d in data" :key="d.code" :label="d.code">{{ d.name }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </c-common-search-mdm>
          </el-form-item>
          <el-form-item prop="name" label="门店名称">
            <el-input v-model.trim="formDataShopDTO.name" placeholder="门店名称" clearable />
          </el-form-item>
          <el-form-item prop="shopClassify" label="门店类型">
            <c-common-search-mdm
              v-model="formDataShopDTO.shopClassify"
              :label.sync="formDataShopDTO.shopClassifyName"
              placeholder="请选择"
              cust-doc-code="QY028"
            />
          </el-form-item>
          <el-form-item prop="countryCode" label="国别">
            <c-common-search-mdm-country
              v-model="formDataShopDTO.countryCode"
              :label.sync="formDataShopDTO.countryName"
            />
          </el-form-item>
          <template v-if="isCN">
            <el-form-item prop="province" label="省份">
              <c-common-search-province
                v-model="formDataShopDTO.province"
                value-key="id"
                :label.sync="formDataShopDTO.provinceName"
              />
            </el-form-item>
            <el-form-item prop="city" label="城市">
              <c-common-search-not-province
                v-model="formDataShopDTO.city"
                value-key="id"
                :label.sync="formDataShopDTO.cityName"
                :disabled="!formDataShopDTO.province"
                :depend-on-observe="formDataShopDTO.province"
                :start-observe="startObserve"
                :parent-id="formDataShopDTO.province"
              />
            </el-form-item>
            <el-form-item prop="county" label="区/县">
              <c-common-search-not-province
                v-model="formDataShopDTO.county"
                value-key="id"
                :label.sync="formDataShopDTO.countyName"
                :disabled="!formDataShopDTO.city"
                :depend-on-observe="formDataShopDTO.city"
                :start-observe="startObserve"
                :parent-id="formDataShopDTO.city"
              />
            </el-form-item>
            <el-form-item prop="town" label="街道/乡镇">
              <c-common-search-not-province
                v-model="formDataShopDTO.town"
                value-key="id"
                :label.sync="formDataShopDTO.townName"
                :disabled="!formDataShopDTO.county"
                :depend-on-observe="formDataShopDTO.county"
                :start-observe="startObserve"
                :parent-id="formDataShopDTO.county"
              />
            </el-form-item>
          </template>
          <el-form-item prop="shopAddr" label="详细地址" :span="24">
            <el-input v-model="formDataShopDTO.shopAddr" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows:2}" placeholder="详细地址" clearable />
          </el-form-item>
          <el-form-item prop="floor" label="所在楼层">
            <el-input v-model="formDataShopDTO.floor" placeholder="所在楼层" clearable />
          </el-form-item>
          <el-form-item prop="cityLevel" label="城市级别">
            <c-dict-select v-model="formDataShopDTO.cityLevel" :label.sync="formDataShopDTO.cityLevelName" dict-type-code="CITY_LEVEL" clearable placeholder="城市级别" style="width:100%" />
          </el-form-item>
          <el-form-item prop="marketLevelCode" label="市场层级">
            <c-dict-select v-model="formDataShopDTO.marketLevelCode" :label.sync="formDataShopDTO.marketLevelName" dict-type-code="MARKET_LEVEL" clearable placeholder="市场层级" style="width:100%" />
          </el-form-item>
          <el-form-item prop="shopInfoPhone" label="门店咨询电话">
            <el-input v-model="formDataShopDTO.shopInfoPhone" placeholder="门店咨询电话" clearable />
          </el-form-item>
          <el-form-item prop="shopServPhone" label="售后电话">
            <el-input v-model="formDataShopDTO.shopServPhone" placeholder="售后电话" clearable />
          </el-form-item>
          <el-form-item prop="outpicArea" label="出图总面积(㎡)">
            <el-input v-model="formDataShopDTO.outpicArea" v-number.float="2" placeholder="出图总面积(㎡)" clearable />
          </el-form-item>
          <el-form-item prop="isDecorationDoorHead" label="是否装修门头">
            <c-dict-select v-model="formDataShopDTO.isDecorationDoorHead" dict-type-code="BOOLEANS" clearable placeholder="是否装修门头" style="width:100%" />
          </el-form-item>
          <el-form-item prop="doorHeadArea" label="门头面积(㎡)">
            <el-input v-model="formDataShopDTO.doorHeadArea" v-number.float="2" placeholder="门头面积(㎡)" clearable />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS055" label="营业执照图片" :span="24">
            <c-file-list v-model="formDataShopDTO.ACCESS055" direct-del :model-id="formDataShopDTO.id" view-type="list" type-code="ACCESS055" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS056" label="专卖店特许经营合同图片" label-width="160px" :span="24">
            <c-file-list v-model="formDataShopDTO.ACCESS056" direct-del :model-id="formDataShopDTO.id" view-type="list" type-code="ACCESS056" />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <template v-if="!isTakeOver">
      <c-title title="门店-联系人">
        <ContactsTable ref="shopContactsTable" title="门店-联系人" :table-data="shopContactsTableData" :exclude-requireds="['email']" type="edit" />
      </c-title>
      <c-title title="门店报图情况">
        <QupFormContainer :column="1">
          <el-form ref="form4" :model="formDataShopDTO" :rules="formRules3" label-width="110px">
            <el-form-item prop="isReportPic" label="是否报图">
              <!-- <el-switch v-model="formDataShopDTO.isReportPic" :active-value="1" :inactive-value="0" /> -->
              <c-dict-select v-model="formDataShopDTO.isReportPic" dict-type-code="BOOLEANS" clearable placeholder="是否报图" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS057" label="特殊建档附件" :span="24">
              <c-file-list v-model="formDataShopDTO.ACCESS057" direct-del tip="如未报图/未交保证金等情况，业务请示申请审核通过的流程附件" :model-id="formDataShopDTO.id" view-type="list" type-code="ACCESS057" />
            </el-form-item>
          </el-form>
        </QupFormContainer>
      </c-title>
    </template>

    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSave">保存</c-button>
      <c-button type="primary" @click="handleSubmit">提交</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { archiveDetail, archiveSaveOrSubmit } from '@/api/channelTask2/newArchive'
import { downTemplate, getTemplateConfig } from '@/api/channelTask2/change'

function fileValidate(rule, required = true) {
  return [
    { required: required,
      validator: function(r, v, c) {
        if (!required) {
          c()
          return
        }
        if (!v || !(v instanceof Array) || v.length === 0) {
          c(rule[0].message)
        } else {
          c()
        }
      },
      trigger: 'change' }
  ]
}

import AddrTable from '../../components/AddrTable'
import ContactsTable from '../../components/ContactsTable'
import PartnershipTable from '../../components/PartnershipTable'
import DistributionTable from '../../components/DistributionTable'
import { validIDCard } from '@/utils/validate'
import ShopTable from './ShopTable'
import ShopContactTable from './ShopContactTable'
import { getShopByCustomerCode, getShopContactByShopCode } from '@/api/channelTask2/newArchive'
const validatorIdCard = (r, v, c) => {
  if (!validIDCard(v)) {
    c(new Error('身份证格式错误'))
    return
  }
  c()
}
export default {
  name: 'AddEdit',
  components: {
    AddrTable,
    ContactsTable,
    PartnershipTable,
    DistributionTable,
    ShopTable,
    ShopContactTable
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {},
      loading: false,
      startObserve: false,
      formData: {
        accountCode: '', // 账号编码
        accountName: '', // 账号名称
        accountTypeCode: '', // 账号类型编码
        accountTypeName: '', // 账号类型名称
        addressDTOS: [],
        afterBusinessType: '', // 调整后客户业务类型
        applyNo: '', // BPM流程单号
        businessTypeCode: '', // 客户经营类型编码
        businessTypeName: '', // 客户经营类型名称
        code: '', // 单号
        contactDTOS: [],
        contactPhone: '', // 经销商联系电话
        cooperateStart: '', // 合作起始日期
        createBy: '', // 申请人
        createTime: '', // 申请时间
        credentialNo: '', // 身份证号
        customerCode: '', // 客户编码
        customerName: '', // 客户名称（经销商系统名称）
        disAddr: '', // 身份证详细地址
        handoverDTOS: [],
        id: '', // ID
        isChangeAccount: '', // 是否变更业务账号
        isChangeBusinessType: '', // 是否变更客户业务类型
        isElecBusiniess: '', // 是否有电商配送权限
        isMarketConnect: '', // 是否交接
        isPartnership: '', // 是否合伙经营
        legalPerson: '', // 法人代表（经销商姓名）
        marketLevelName: '', // 市场级别名称
        officeCode: '', // 办事处编码
        officeName: '', // 办事处名称
        officeTypeCode: '', // 办事处类型编码
        officeTypeName: '', // 办事处类型名称
        operateArea: '', // 客户经营总面积
        partnerDTOS: [],
        personCode: '', // 办事处负责人编码
        personName: '', // 办事处负责人名称
        isOtherReceiveManagerKnow: '', // 是否需要其他客户经理知晓
        receiveManagerCode: '', // 数据接收客户经理编码
        receiveManagerName: '', // 数据接收客户经理名称
        receiveManagerTel: '', // 数据接收客户经理电话
        receiveManagerTypeCode: '', // 数据接收客户经理类别编码
        receiveManagerTypeName: '', // 数据接收客户经理类别名称
        reportManagerCode: '', // 提报客户经理编码
        reportManagerName: '', // 提报客户经理名称
        reportManagerTel: '', // 提报客户经理电话
        reportManagerTypeCode: '', // 提报客户经理类别编码
        reportManagerTypeName: '', // 提报客户经理类别名称
        submitAnOpinion: '', // 提报意见
        reviewAdvice: '', // 审核意见
        reviewResult: '', // 审核结果
        reviewTime: '', // 审核时间
        schedule: '', // 进度
        shopDTOS: [],
        type: '', // 单据类型
        isTakeOverTheOriginalStore: '', // 是否接管原商家门店
        // 附件
        ACCESS050: [],
        ACCESS051: [],
        ACCESS052: [],
        ACCESS053: [],
        ACCESS054: [],
        ACCESS058: [],
        ACCESS059: [],
        ACCESS111: []
      },
      businessTypeData: [], // 门店业务类型数据
      formDataShopDTO: {
        businessType: [],
        businessTypeName: [],
        name: '',
        shopClassify: '',
        countryCode: 'CN',
        countryName: '中国',
        province: '',
        city: '',
        county: '',
        town: '',
        shopAddr: '',
        floor: '',
        cityLevel: '',
        marketLevelCode: '',
        shopInfoPhone: '',
        shopServPhone: '',
        outpicArea: '',
        isDecorationDoorHead: '',
        isReportPic: '',
        doorHeadArea: '',
        ACCESS055: [],
        ACCESS056: [],
        ACCESS057: []
      }, // 门店基本信息
      shopLoading: false,
      disContactsTableData: [], // 经销商联系人
      shopContactsTableData: [], // 门店联系人
      isHandoverDistribution: '0', // 是否交接分销客户
      ACCESS111: {}, // 附件配置
      customerShopData: [], // 客户门店
      shopContactsData: [] // 交接时门店自动带出的联系人
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    formRules() {
      return {
        officeCode: [{ required: true, message: '请选择办事处', trigger: 'change' }],
        receiveManagerCode: [{ required: [1, '1'].includes(this.formData.isOtherReceiveManagerKnow), message: '请选择接收客户经理', trigger: 'change' }]
      }
    },
    formRules2() {
      return {
        // 经销商基本信息
        customerName: [{ required: true, message: '请输入经销商系统名称', trigger: 'change' }],
        legalPerson: [{ required: true, message: '请输入经销商姓名', trigger: 'change' }],
        credentialNo: [
          { required: true, message: '请输入经销商身份证号', trigger: 'change' },
          { validator: validatorIdCard, trigger: 'change' }
        ],
        disAddr: [{ required: true, message: '请输入身份证详细地址', trigger: 'change' }],
        cooperateStart: [{ required: true, message: '请选择合作起始日期', trigger: 'change' }],
        ACCESS050: fileValidate([{ required: true, message: '请上传身份证正面图片', trigger: 'change' }]),
        ACCESS051: fileValidate([{ required: true, message: '请上传身份证反面图片', trigger: 'change' }]),
        ACCESS052: fileValidate([{ required: true, message: '请上传资金安全告知函', trigger: 'change' }]),
        ACCESS053: fileValidate([{ required: true, message: '请上传签字签章函', trigger: 'change' }]),
        ACCESS054: fileValidate([{ required: true, message: '请上传收货地址确认单', trigger: 'change' }])
      }
    },
    isCN() {
      return this.formDataShopDTO.countryCode === 'CN'
    },
    formRules3() {
      return {
        // 门店基本信息
        businessType: [{ required: true, message: '请选择门店经营业务类型', trigger: 'change' }],
        name: [{ required: true, message: '请输入门店名称', trigger: 'change' }],
        shopClassify: [{ required: true, message: '请选择门店类型', trigger: 'change' }],
        countryCode: [{ required: true, message: '请选择国别', trigger: 'change' }],
        province: [{ required: this.isCN, message: '请选择省份', trigger: 'change' }],
        city: [{ required: this.isCN, message: '请选择城市', trigger: 'change' }],
        county: [{ required: this.isCN, message: '请选择区/县', trigger: 'change' }],
        town: [{ required: this.isCN, message: '请选择街道/乡镇', trigger: 'change' }],
        shopAddr: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
        floor: [{ required: true, message: '请输入所在楼层', trigger: 'change' }],
        cityLevel: [{ required: true, message: '请选择城市级别', trigger: 'change' }],
        marketLevelCode: [{ required: true, message: '请选择市场层级', trigger: 'change' }],
        shopInfoPhone: [{ required: true, validator: (r, v, c) => {
          if (!v) {
            c(new Error('请输入门店咨询电话'))
          } else if (!/^\d{3,4}-\d{7,8}$|^1\d{10}$/.test(v)) {
            c(new Error('请检查号码格式!'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        shopServPhone: [{ required: true, validator: (r, v, c) => {
          if (!v) {
            c(new Error('请输入售后电话'))
          } else if (!/^\d{3,4}-\d{7,8}$|^1\d{10}$/.test(v)) {
            c(new Error('请检查号码格式!'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        outpicArea: [{ required: true, message: '请输入出图总面积(㎡)', trigger: 'change' }],
        isDecorationDoorHead: [{ required: true, message: '请选择是否装修门头', trigger: 'change' }],
        doorHeadArea: [{ required: [1, '1'].includes(this.formDataShopDTO.isDecorationDoorHead), message: '请输入门头面积(㎡)', trigger: 'change' }],
        ACCESS055: fileValidate([{ required: true, message: '请上传营业执照图片', trigger: 'change' }]),
        ACCESS056: fileValidate([{ required: true, message: '请上传专卖店特许经营合同图片', trigger: 'change' }]),
        // 报图相关
        isReportPic: [{ required: true, message: '请选择是否报图', trigger: 'change' }]
        // ACCESS057: fileValidate([{ required: true, message: '请上传特殊建档附件', trigger: 'change' }])
      }
    },
    formRules6() {
      return {
        isTakeOverTheOriginalStore: [{ required: true, message: '请选择是否接管原商家门店', trigger: 'change' }]
      }
    },
    formRules4() {
      return {
        // 交接信息
        isMarketConnect: [{ required: true, message: '请选择是否经销商交接', trigger: 'change' }],
        ACCESS058: fileValidate([{ required: true, message: '请上传经销商交接证明', trigger: 'change' }]),
        ACCESS059: fileValidate([{ required: true, message: '请上传经销商关系证明', trigger: 'change' }], this.hasIsTransferSales),
        ACCESS111: fileValidate([{ required: true, message: '请上传交接双方现场签订照片', trigger: 'change' }], this.hasIsMarketConnect)
      }
    },
    showReceiveManager() {
      return [1, '1'].includes(this.formData.isOtherReceiveManagerKnow)
    },
    hasIsTransferSales() {
      return this.formData.handoverDTOS.some(e => [1, '1'].includes(e.isTransferSales))
    },
    hasIsMarketConnect() {
      return [1, '1'].includes(this.formData.isMarketConnect)
    },
    // 是否接管
    isTakeOver() {
      return this.hasIsMarketConnect && [1, '1'].includes(this.formData.isTakeOverTheOriginalStore)
    }
  },
  created() {
    if (!this.id) {
      this.startObserve = true
    } else {
      this.getDetailData().then(() => {
        setTimeout(() => {
          this.startObserve = true
        }, 0)
      })
    }
    this.templateConfig()
  },
  mounted() {
    this.$nextTick(() => {
      const forms = 'form form2 form3 form4 form5'.split(' ')
      forms.forEach(f => {
        const ref = this.$refs[f]
        if (ref && ref.clearValidate) {
          ref.clearValidate()
        }
      })
    })
  },
  methods: {
    async validate() {
      const forms = 'form form2 form3 form4 form5 form6'.split(' ')
      for (const f of forms) {
        const ref = this.$refs[f]
        if (ref && ref.validate) {
          await ref.validate()
        }
      }
      // 校验经销商-收货地址 至少有一条收货地址数据
      if (this.formData.addressDTOS.length <= 0) {
        const msg = '请填写经销商-收货地址!'
        this.$message.warning(msg)
        return Promise.reject(msg)
      }
      const one = [1, '1']
      // 校验经销商-联系人 至少有一条联系人类别为“责任人”的数据；
      if (!this.disContactsTableData.some(e => one.includes(e.contactTypeCode))) {
        const msg = '至少有一条【经销商-联系人类别】为【责任人】!'
        this.$message.warning(msg)
        return Promise.reject(msg)
      }
      // 合伙经营 当合伙经营为是时，至少有一条合伙人数据；
      if (one.includes(this.formData.isPartnership) && this.formData.partnerDTOS.length <= 0) {
        const msg = '当合伙经营为是时，至少有一条合伙人数据!'
        this.$message.warning(msg)
        return Promise.reject(msg)
      }
      // 门店联系人 至少有一条联系人类别为“责任人”的数据；
      if (!this.isTakeOver) {
        if (!this.shopContactsTableData.some(e => one.includes(e.contactTypeCode))) {
          const msg = '至少有一条【门店-联系人类别】为【责任人】!'
          this.$message.warning(msg)
          return Promise.reject(msg)
        }
      }
      // 交接信息
      if (one.includes(this.formData.isMarketConnect) && this.formData.handoverDTOS.length === 0) {
        const msg = '【交接信息】至少有一条数据!'
        this.$message.warning(msg)
        return Promise.reject(msg)
      }
      // 校验table
      const keys = 'addrTable contactsTable partnershipTable shopContactsTable distributionTable shopTable shopContactTable'.split(' ')
      for (const k of keys) {
        const ref = this.$refs[k]
        if (ref && ref.validate) {
          await ref.validate()
        }
      }
      return Promise.resolve(true)
    },
    getDetailData() {
      this.loading = true
      return archiveDetail(this.id).then(res => {
        this.loading = false
        if (!res.data.shopDTOS) {
          res.data.shopDTOS = []
        }
        this.detail = res.data
        this.initFormData()
        // 处理是否交接分销客户
        // this.isHandoverDistribution = this.detail.handoverDTOS.some(e => [1, '1'].includes(e.isHandoverDistribution)) ? '1' : '0'
        this.isHandoverDistribution = this.detail.isHandoverDistribution
      }).catch(res => {
        this.loading = false
        return Promise.reject(res)
      })
    },
    initFormData() {
      Object.keys(this.formData).forEach(k => {
        const v = this.detail[k]
        if (v === undefined) {
          return
        }
        this.$set(this.formData, k, v)
      })
      // 门店
      const isTakeOver = [1, '1'].includes(this.detail.isMarketConnect) && [1, '1'].includes(this.detail.isTakeOverTheOriginalStore)
      if (isTakeOver) {
        const d = this.$deepClone(this.detail)
        // 新增和编辑时同步shopBusinessId
        const codes = (this.detail.handoverDTOS || []).map(e => e.fromCustomerCode)
        codes.length > 0 && getShopByCustomerCode(codes).then(res => {
          // this.customerShopData = res.data
          this.customerShopData = (d.shopDTOS || []).map(e => {
            const t = (res.data || []).find(ee => ee.originalCode === e.originalCode)
            if (t) {
              e.shopBusinessId = t.shopBusinessId
              e.originalName = t.originalName
            }
            return e
          })
        })
        this.shopContactsData = (d.contactDTOS || []).filter(e => [3, '3'].includes(e.contactScope))
      } else {
        this.formDataShopDTO = Object.assign(this.formDataShopDTO, this.detail.shopDTOS[0] || {})
        if (!(this.formDataShopDTO.businessType instanceof Array)) {
          this.$set(this.formDataShopDTO, 'businessType', (this.formDataShopDTO.businessType || '').split(',').filter(e => e !== ''))
          this.$set(this.formDataShopDTO, 'businessTypeName', (this.formDataShopDTO.businessTypeName || '').split(',').filter(e => e !== ''))
        }
      }

      const one = [1, '1']
      const two = [3, '3']
      // 经销商联系人
      this.disContactsTableData = (this.detail.contactDTOS || []).filter(e => one.includes(e.contactScope))
      // 门店联系人
      if (!isTakeOver) {
        this.shopContactsTableData = (this.detail.contactDTOS || []).filter(e => two.includes(e.contactScope))
      }
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleBusinessTypeDataChange(v) {
      this.businessTypeData = v
    },
    handleBusinessChange(v) {
      this.formDataShopDTO.businessTypeName = this.businessTypeData.filter(e => v.includes(e.code)).map(e => e.name)
    },
    getPostData() {
      const data = {}
      if (this.isEdit) {
        Object.assign(data, this.$deepClone(this.detail))
      }
      Object.assign(data, this.$deepClone(this.formData))
      // contactScope 1 客户 3 门店
      data.contactDTOS = [...this.disContactsTableData.map(e => {
        e = this.$deepClone(e)
        e.contactScope = 1
        return e
      })]
      // 处理门店联系人
      if (!this.isTakeOver) {
        data.contactDTOS = data.contactDTOS.concat(this.shopContactsTableData.map(e => {
          e = this.$deepClone(e)
          e.contactScope = 3
          return e
        }))
      } else {
        data.contactDTOS = data.contactDTOS.concat(this.$refs.shopContactTable.getData())
      }

      if (!this.isTakeOver) {
        const shopDTO	= Object.assign({}, this.$deepClone(this.formDataShopDTO))
        shopDTO.attachmentDTOS = [
          ...this.$getFiles(this.formDataShopDTO.ACCESS055 || []),
          ...this.$getFiles(this.formDataShopDTO.ACCESS056 || []),
          ...this.$getFiles(this.formDataShopDTO.ACCESS057 || [])
        ]
        'ACCESS055 ACCESS056 ACCESS057'.split(' ').forEach(k => {
          delete shopDTO[k]
        })
        shopDTO.businessType = (shopDTO.businessType || []).join(',')
        shopDTO.businessTypeName = (shopDTO.businessTypeName || []).join(',')
        data.shopDTOS = [shopDTO]
      } else {
        data.shopDTOS = this.$refs.shopTable.getData()
      }

      if (![1, '1'].includes(data.isPartnership)) {
        data.partnerDTOS = []
      }

      const isMCTrue = [1, '1'].includes(data.isMarketConnect)

      data.attachmentDTOS = [
        ...this.$getFiles(this.formData.ACCESS050 || []),
        ...this.$getFiles(this.formData.ACCESS051 || []),
        ...this.$getFiles(this.formData.ACCESS052 || []),
        ...this.$getFiles(this.formData.ACCESS053 || []),
        ...this.$getFiles(this.formData.ACCESS054 || [])

      ]
      if (isMCTrue) {
        data.attachmentDTOS.push(
          ...this.$getFiles(this.formData.ACCESS058 || []),
          ...this.$getFiles(this.formData.ACCESS059 || []),
          ...this.$getFiles(this.formData.ACCESS111 || [])
        )
      }
      'ACCESS050 ACCESS051 ACCESS052 ACCESS053 ACCESS054 ACCESS058 ACCESS059 ACCESS111'.split(' ').forEach(k => {
        delete data[k]
      })
      data.type = 'A'
      // 进度处理
      if (this.isEdit) {
        data.schedule = 'A'
      } else {
        data.schedule = 'B'
      }
      // 是否交接分销客户
      if (!isMCTrue) {
        data.handoverDTOS = []
      }
      data.handoverDTOS.forEach(e => {
        e.isHandoverDistribution = this.isHandoverDistribution
      })
      data.isHandoverDistribution = this.isHandoverDistribution
      return data
    },
    handleSave() {
      const data = this.getPostData()
      data.schedule = 'A'
      return archiveSaveOrSubmit(data).then(res => {
        this.$message.success('操作成功!')
        this.$pageStack.pop('onPage')
      })
    },
    handleSubmit() {
      return this.validate().then(() => {
        const data = this.getPostData()
        data.schedule = 'B'
        return archiveSaveOrSubmit(data).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    handleChange(v) {
      if (![1, '1'].includes(v)) {
        this.$refs.cCommonSearchPerson.handleInput('')
      }
    },
    handleDownTemplate(id) {
      downTemplate(id)
    },
    templateConfig() {
      getTemplateConfig('ACCESS111').then(res => {
        this.ACCESS111 = res
      })
    },
    // 根据客户编码获取门店
    getCustomerShop(codes) {
      this.customerShopData = []
      if (codes.length <= 0) return
      return getShopByCustomerCode(codes).then(res => {
        this.customerShopData = res.data
        this.shopContactsData = []
      })
    },
    // 根据门店编码获取门店联系人
    getShopContact(shop, id) {
      return getShopContactByShopCode(shop.originalCode).then(res => {
        this.shopContactsData.push(...(res.data || []).map(e => {
          e.contactTypeCode = '1'
          e.contactTypeName = '责任人'
          e.isAutoAdd = '0'
          e.isChange = '1'
          e.shopBusinessId = id
          e.address = ''
          e.contactFax = ''
          e.contactId = ''
          e.contactPhone = ''
          e.contactTel = ''
          e.email = ''
          e.name = ''
          e.customerCode = ''
          e.shopCode = ''
          e.shopName = ''
          e.shopAddress = shop.shopAddr
          return e
        }))
      })
    },
    handleOnCustomerChange(codes) {
      this.$set(this.formData, 'isTakeOverTheOriginalStore', '')
      this.customerShopData = []
      this.shopContactsData = []
      this.getCustomerShop(codes)
    },
    handleOfficeChange() {
      this.customerShopData = []
      this.shopContactsData = []
    },
    handleOnTakeoverChange(v, row) {
      if ([1, '1'].includes(v)) {
        this.getShopContact(row, row.shopBusinessId || row.id)
      } else {
        this.shopContactsData = this.shopContactsData.filter(e => e.shopBusinessId !== row.shopBusinessId || [1, '1'].includes(e.isAutoAdd))
      }
    },
    handleTakeOverChange(v) {
      if ([1, '1'].includes(v)) {
        this.getCustomerShop((this.formData.handoverDTOS || []).map(e => e.fromCustomerCode))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.handover{
  display: flex;
  align-items: center;
  .tip{
    padding-left: 10px;
    color: red;
  }
}
.template-down{
    // display: flex;
    // align-content: center;
    display: inline-block;
    cursor: pointer;
    &>*{
      margin-right: 10px;
      color: #333;
      font-weight: 600;
    }
}
</style>
